package com.example.emojibase.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.example.emojibase.R;
import com.example.emojibase.pojo.Emoji;

import java.util.ArrayList;
import java.util.List;

public class EmojiAdapter extends RecyclerView.Adapter<EmojiAdapter.RecyclerHolder> {

    private Context mContext;
    private List<Emoji> emojis = new ArrayList<>();
    private static EmojiAdapter sInstance;
    private OnItemClickListener listener;

    private EmojiAdapter(Context context) {
        mContext = context;
    }

    public static synchronized EmojiAdapter getInstance(Context context){
        if (sInstance == null) {
            sInstance = new EmojiAdapter(context.getApplicationContext());
        }
        return sInstance;
    }

    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }

    // 设置点击监听器的方法
    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }


    public void setData(List<Emoji> emojis) {
        if (null != this.emojis) {
            this.emojis.clear();
            this.emojis.addAll(emojis);
            notifyDataSetChanged();
        }
    }

    @Override
    public RecyclerHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.emoji_item, parent, false);
        return new RecyclerHolder(view);
    }

    @Override
    public void onBindViewHolder(RecyclerHolder holder, int position) {
        Emoji emoji=emojis.get(position);
        holder.textView.setText(emoji.getName());
        Bitmap imagebitmap = BitmapFactory.decodeByteArray(emoji.getAvatar(), 0, emoji.getAvatar().length);
        holder.imgView.setImageBitmap(imagebitmap);
        holder.itemView.setOnClickListener(view -> {
            if (listener != null) {
                listener.onItemClick(view, position);
            }
        });
    }

    @Override
    public int getItemCount() {
        return emojis.size();
    }

    class RecyclerHolder extends RecyclerView.ViewHolder {
        ImageView imgView;
        TextView textView;

        private RecyclerHolder(View itemView) {
            super(itemView);
            imgView = itemView.findViewById(R.id.emojiImageView);
            textView = itemView.findViewById(R.id.emojiNameTextView);
        }
    }

    public Emoji getEmojiByPosition(int postion) {
        return emojis.get(postion);
    }

    public void removeEmojiByPosition(int position) {
        emojis.remove(position);
        notifyDataSetChanged();
    }

}